package com.streambolics.worseminton.data;

import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.streambolics.data.Person;
import com.streambolics.std.HtmlBuilder;

/**
 * The base class of all persistent objects that include a guest.
 * 
 * @author Sauron
 * 
 */

@PersistenceCapable(identityType = IdentityType.APPLICATION)
@Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
public class WorsemintonGuestObject extends WorsemintonPersistentObject
{

    @Persistent
    long   guestId;

    @NotPersistent
    Person _Guest;

    protected WorsemintonGuestObject(long aGuestId)
    {
        guestId = aGuestId;
    }

    /**
     * Generate an HTML snippet with the name of the guest, with the appropriate
     * color and style;
     * 
     * @param aBuilder
     */

    public void generateNameText (HtmlBuilder aBuilder)
    {
        aBuilder.addSpan (getNameHtmlStyle (), getGuest ().getBestName ());
    }

    public Person getGuest ()
    {
        if (_Guest == null)
        {
            _Guest = Person.load (getDatabase (), guestId);
        }
        return _Guest;
    }

    public long getGuestId ()
    {
        return guestId;
    }

    /**
     * The style to use for displaying the name.
     * 
     * @return The name of a CSS class to be used to display the name of the
     *         guest.
     */

    public String getNameHtmlStyle ()
    {
        return "";
    }

    /**
     * Whether this object is addressed to the given user.
     * 
     * An object is addressed to a given user if either:
     * <ul>
     * <li>
     * The user is indeed the referenced guest</li>
     * <li>
     * There is no user, and the guest has not locked his account.</li>
     * </ul>
     * 
     * @param aUserId
     *            The internal user id of the logged-in user, or -1 to indicate
     *            that no one is logged in.
     * 
     * @return True if aUserId can be reasonably considered to be the intended
     *         recipient of the object.
     */

    public boolean isAddressedTo (long aUserId)
    {
        return getGuestId () == aUserId || (aUserId == -1 && getGuest ().isUnregistered ());
    }

    /**
     * Whether this object can be modified by the given user.
     * 
     * The object can be modified if either:
     * <ul>
     * <li>The user is the addressee</li>
     * <li>
     * The guest has not protected his account</li>
     * </ul>
     * 
     * @param aUserId
     * @return
     */

    public boolean mayBeModifiedBy (long aUserId)
    {
        return isAddressedTo (aUserId) || getGuest ().isUnregistered ();
    }
}
